#pragma once

#include <mutex>
#include "esp_netif.h"
#include "lwip/tcp.h"
#include "AcHandler.hpp"

class Async;
class AsyncClient;

class AsyncServer {
public:
    AsyncServer(ip_addr_t addr, uint16_t port);
    AsyncServer(uint16_t port);
    ~AsyncServer();
    void  begin();
    void  end();
    void  set_connected_handler(AcConnectHandler handler, void* arg);
    void  set_nodelay(bool nodelay);
    bool  get_nodelay();
    void  push_client_to_pool(AsyncClient* client);
    err_t handle_accepted_event(AsyncClient* client);
    tcp_state get_connection_state();

private:
    uint8_t      init_client_pool();
    AsyncClient* get_client_from_pool();
    err_t        create_accept_event(void* arg, AsyncClient* client);
    err_t        bind();

    uint16_t            m_port;                 // 监听端口
    ip_addr_t           m_addr;                 // 监听地址
    bool                m_nodelay;              // 客户端全局迟延功能配置
    tcp_pcb*            m_pcb;                  // 关联的连接（协议控制块）
    Async*              m_async;                // 关联异步处理实例
    std::mutex          m_pool_mutex;           // 连接池锁
    QueueHandle_t       m_client_pool;          // 连接池（客户端池）
    AcConnectHandler    on_connected_handler;   // 用户连接处理回调
    void*               on_connected_arg;       // 用户连接处理回调参数
};